#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UIThreePartButton.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UIView-Hierarchy.h>
#import <UIKit/UITextView.h>
#import <UIKit/UIHardware.h>
#import <UIKit/UIView-Geometry.h>
#import <UIKit/UINavBarButton.h>
#import "MTApp.h"
#import "MTTetrominosView.h"
#import "MTTetrominosPreviewPane.h"
#import "MTTetrominosEngine.h"


#import <UIKit/UIKit.h>
#import <UIKit/UIView.h>
#import <UIKit/UITableCell.h>
#import <UIKit/UITextLabel.h>
#import <UIKit/UITransformAnimation.h>
#import <UIKit/UIAnimator.h>
//#import <CoreGraphics/CoreGraphics.h>

@implementation MobileTetrominos

- (void) applicationDidFinishLaunching: (id) unused
{
	NSLog(@"MobileTetrominos entered applicationDidFinishLaunching");


	_appLibraryPath = [[self userLibraryDirectory] stringByAppendingPathComponent: @"MobileTetrominos"];
	_appSettingsPath = [_appLibraryPath stringByAppendingPathComponent: @"Settings.plist"];
	_appSuspendSaveStatePath = [_appLibraryPath stringByAppendingPathComponent: @"SuspendSavedState.plist"];
	
	[[NSFileManager defaultManager] createDirectoryAtPath: _appLibraryPath attributes: nil];
	
	[_appLibraryPath retain];
	[_appSettingsPath retain];
	[_appSuspendSaveStatePath retain];
	 
	_turnTime = 0.0;
	_paused = FALSE;
		
	//Set up the Tetrominos Engine.
	_TetrominosEngine = [[MTTetrominosEngine alloc] init];
	[_TetrominosEngine startEngine];

	// Set up a window.
	_windowRect = [UIHardware fullScreenApplicationContentRect];
	_window = [[UIWindow alloc] initWithContentRect: _windowRect];
    [_window orderFront: self];
    [_window makeKey: self];
    [_window _setHidden: NO];
	
	//Set up the main view (for the window).
	_mainViewRect = _windowRect;
	_mainViewRect.origin.x = 0.0f;
	_mainViewRect.origin.y = 0.0f;
    _mainView = [[UIView alloc] initWithFrame: _mainViewRect];
	[_window setContentView: _mainView];
	
		//Set up the Nav Bar
	_navBarRect = _windowRect;
	_navBarRect.origin.x = 0.0f;
	_navBarRect.origin.y = 0.0f;
	_navBarRect.size.height = 40.0f;
	_navBar = [[UINavigationBar alloc] initWithFrame: _navBarRect];
	[_navBar setBarStyle: 0];
	[_navBar setDelegate: self];
	
	//Set up Nav Bar buttons
	_newGameButton = [_navBar createButtonWithContents: @"New Game" 
		width: 32.0f 
		barStyle: 0
		buttonStyle: 0
		isRight: FALSE];
	[_newGameButton setFrame: CGRectMake(10.0f, 5.0f, 90.0f, 30.0f)];
	[_newGameButton addTarget: self action: @selector(newGameButtonPressed) forEvents: 1];
	[_navBar addSubview: _newGameButton];
	
	_pauseButton = [_navBar createButtonWithContents: @"Pause"
		width: 32.0f
		barStyle: 0
		buttonStyle: 0
		isRight: FALSE];
	[_pauseButton setFrame: CGRectMake(110.0f, 5.0f, 90.0f, 30.0f)];
	[_pauseButton addTarget: self action: @selector(pauseButtonPressed) forEvents: 1];
	[_navBar addSubview: _pauseButton];

	[_mainView addSubview: _navBar];
	
	//Set up the Tetrominos view
	_TetrominosViewRect = _mainViewRect;
	_TetrominosViewRect.size.height = _TetrominosViewRect.size.height - _navBarRect.size.height;
	_TetrominosViewRect.size.width = _TetrominosViewRect.size.height / 2;
	_TetrominosViewRect.origin.y = _mainViewRect.origin.y + _navBarRect.size.height;
	_TetrominosView = [[MTTetrominosView alloc] initWithEngine: _TetrominosEngine
	WithFrame: _TetrominosViewRect];
	[_mainView addSubview: _TetrominosView];

	//Set up the infobar.
	_infoBarRect = _mainViewRect;
	_infoBarRect.size.width = _mainViewRect.size.width - _TetrominosViewRect.size.width;
	_TetrominosViewRect.size.height = _TetrominosViewRect.size.height - _navBarRect.size.height;
	_infoBarRect.origin.x = _TetrominosViewRect.size.width;
	_infoBarRect.origin.y = _navBarRect.size.height;
	_infobarView = [[UIImageView alloc] initWithFrame: _infoBarRect];
	[_infobarView setOpaque: TRUE];
	[_infobarView setImage: [UIImage applicationImageNamed: @"sidebar.png"]];
	[_infobarView setFrame: _infoBarRect];
	[_mainView addSubview: _infobarView];
	
	//Set up the labels.
	CGRect labelFrame = CGRectMake(5.0f, 100.0f, _infoBarRect.size.width - 5.0f, 20.0f);
	_speedLabel = [[UITextLabel alloc] initWithFrame: labelFrame];
	labelFrame.origin.y += 20.0f;
	_scoreLabel = [[UITextLabel alloc] initWithFrame: labelFrame];
	labelFrame.origin.y += 35.0f;
	_previewLabel = [[UITextLabel alloc] initWithFrame: labelFrame];
	
	// TODO: Set up the transparency for labels
	
	//float clearColor[4] = {1, 1, 1, 0};
	//[_scoreLabel setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), clearColor)];
	//[_speedLabel setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), clearColor)];
			
	[_infobarView addSubview: _speedLabel];
	[_infobarView addSubview: _scoreLabel];
	
	//Display icon
	_icon = [[UIImageView alloc] initWithImage: [UIImage applicationImageNamed:@"icon.png"]];
	CGRect iconRect = [_icon frame];
	iconRect.origin.x = (_infoBarRect.size.width * 0.5) - (iconRect.size.width * 0.5);
	iconRect.origin.y = 20.0f;
	[_icon setFrame: iconRect];
	[_infobarView addSubview: _icon];
	
	//Set up buttons.
	float buttonWidth = _infoBarRect.size.width * 0.40f;
	float buttonHeight = 32.0f;
	float originHeightPercent = 0.70f;
	float buttonSpacing = 5.0f;
	float verticalButtonSpacing = 20.0f;
	
	CGRect buttonRect = CGRectMake(5.0f, 5.0f, 32.0f, 40.0f);
	CGRect twoColumnLeftButtonRect = CGRectMake(10.0f, _infoBarRect.size.height * originHeightPercent,
												buttonWidth, buttonHeight);
												
	CGRect twoColumnRightButtonRect = CGRectMake(10.0f + buttonWidth + buttonSpacing,
	                                             _infoBarRect.size.height * originHeightPercent,
												 buttonWidth, buttonHeight);											
		
	CGRect leftButtonRect = twoColumnLeftButtonRect;
	_leftButton = [[UINavBarButton alloc] initWithFrame: leftButtonRect];
	[_leftButton setNavBarButtonStyle: 0];
	[_leftButton setAutosizesToFit: FALSE];
	[_leftButton setTitle: [NSString stringWithUTF8String: "\u21E6"]];
	[_leftButton addTarget: self action: @selector(leftButtonPressed) forEvents: 1];
	[_infobarView addSubview: _leftButton];
	
	CGRect rightButtonRect = twoColumnRightButtonRect;
	_rightButton = [[UINavBarButton alloc] initWithFrame: rightButtonRect];
	[_rightButton setNavBarButtonStyle: 0];
	[_rightButton setAutosizesToFit: FALSE];
	[_rightButton setTitle: [NSString stringWithUTF8String: "\u21E8"]];
	[_rightButton addTarget: self action: @selector(rightButtonPressed) forEvents: 1];
	[_infobarView addSubview: _rightButton];
	
	CGRect rotateLeftButtonRect = twoColumnLeftButtonRect;
	rotateLeftButtonRect.origin.y = leftButtonRect.origin.y - leftButtonRect.size.height - verticalButtonSpacing;
	_rotateLeftButton = [[UINavBarButton alloc] initWithFrame: rotateLeftButtonRect];
	[_rotateLeftButton setNavBarButtonStyle: 0];
	[_rotateLeftButton setAutosizesToFit: FALSE];
	[_rotateLeftButton setTitle: [NSString stringWithUTF8String: "\u21B6"]];
	[_rotateLeftButton addTarget: self action: @selector(rotateLeftButtonPressed) forEvents: 1];
	[_infobarView addSubview: _rotateLeftButton];
	
	CGRect rotateRightButtonRect = twoColumnRightButtonRect;
	rotateRightButtonRect.origin.y = rightButtonRect.origin.y - rightButtonRect.size.height - verticalButtonSpacing;
	_rotateRightButton = [[UINavBarButton alloc] initWithFrame: rotateRightButtonRect];
	[_rotateRightButton setNavBarButtonStyle: 0];
	[_rotateRightButton setAutosizesToFit: FALSE];
	[_rotateRightButton setTitle: [NSString stringWithUTF8String: "\u21B7"]];
	[_rotateRightButton addTarget: self action: @selector(rotateRightButtonPressed) forEvents: 1];
	[_infobarView addSubview: _rotateRightButton];
	
	CGRect downButtonRect = leftButtonRect;
	downButtonRect.origin.x = leftButtonRect.origin.x;
	downButtonRect.origin.y = leftButtonRect.origin.y + leftButtonRect.size.height + verticalButtonSpacing;
	downButtonRect.size.width *= 2;
	downButtonRect.size.width += buttonSpacing;
	
	_downButton = [[UINavBarButton alloc] initWithFrame: downButtonRect];
	[_downButton setNavBarButtonStyle: 0];
	[_downButton setAutosizesToFit: FALSE];
	[_downButton setTitle: [NSString stringWithUTF8String: "\u21E9"]];
	[_downButton addTarget: self action: @selector(downButtonPressed) forEvents: 1];
	[_infobarView addSubview: _downButton];
	
	// Preview Pane
	CGRect previewPaneRect = _infoBarRect;
	previewPaneRect.size.width -= 20.0f;
	previewPaneRect.size.height = previewPaneRect.size.width;
	previewPaneRect.origin.x = 10.0f;
	previewPaneRect.origin.y = 160.0f;
	_previewPane = [[MTTetrominosPreviewPane alloc] initWithFrame: previewPaneRect];
	[_infobarView addSubview: _previewPane];
	
	// Pick up any data from a previous suspend
	[_TetrominosEngine loadStateWithFilename: _appSuspendSaveStatePath delete: TRUE];
	[self resume];
	
	NSLog(@"MobileTetrominos exited applicationDidFinishLaunching");
}

-(void) newGameButtonPressed
{
	[_TetrominosEngine reset];
	_turnTime = [_TetrominosEngine gameSpeed];
	[self setTimers];
	_paused = FALSE;
}

-(void) pauseButtonPressed
{
		if(_paused)		// Already paused
		{
			[self resume];
		}
		else if(!_paused) // Playing, pause
		{
			[self pause];
		}
}

-(void) pause
{
	_paused = TRUE;
	if (_timer != nil)
	{
		[_timer invalidate];
		[_timer release];
		_timer = nil;
	}
}

-(void) resume
{
	_paused = FALSE;
	[self setTimers];
}

-(void) rotateLeftButtonPressed
{
	if(!_paused)
	{
		[_TetrominosEngine rotateLeft];
		[_TetrominosView paint];
	}
}

-(void) rotateRightButtonPressed
{
	if(!_paused)
	{
		[_TetrominosEngine rotateRight];
		[_TetrominosView paint];
	}
}

-(void) leftButtonPressed
{
	if(!_paused)
	{
		[_TetrominosEngine moveLeft];
		[_TetrominosView paint];
	}
}

-(void) rightButtonPressed
{
	if(!_paused)
	{
		[_TetrominosEngine moveRight];
		[_TetrominosView paint];
	}
}

-(void) takeTurn
{
	[_TetrominosEngine heartbeat];
	[_TetrominosView paint];
	[_previewPane setPiece: [_TetrominosEngine nextPiece]];
	[_previewPane paint];
	if ([_TetrominosEngine done])
	{
		[_timer invalidate];
		[_timer release];
		_timer = nil;
	}
	if ([_TetrominosEngine gameSpeed] != _turnTime)
	{
		_turnTime = [_TetrominosEngine gameSpeed];
		[self setTimers];
	}
	
	NSString* labelString = [[[NSString string] stringByAppendingString: @"Level: " ] stringByAppendingString:[[NSString alloc] initWithString: [[NSNumber numberWithFloat: [_TetrominosEngine level]] stringValue]]];
	[_speedLabel setText: [[NSString alloc] initWithString: labelString]];
	labelString = [[[NSString string] stringByAppendingString: @"Lines: " ] stringByAppendingString:[[NSString alloc] initWithString: [[NSNumber numberWithFloat: [_TetrominosEngine score]] stringValue]]];
	[_scoreLabel setText: labelString];
	[_previewLabel setText: @"Next Piece"];
	
}

-(void) downButtonPressed
{
	//[_timer fire];
	[_timer setFireDate: [NSDate dateWithTimeIntervalSinceNow: 0.0]];
}

-(void) setTimers
{
	if (_timer != nil)
	{
		[_timer invalidate];
		[_timer release];
		_timer = nil;
	}
	//Go to takeTurn every _turnTime
	_timer = [ [NSTimer scheduledTimerWithTimeInterval: _turnTime target:self 
				selector:@selector(takeTurn)
				userInfo:nil
				repeats:YES]
				retain
			];
}

- (void) applicationWillSuspend
{
	[self pause];
	[_TetrominosEngine saveStateWithFilename: _appSuspendSaveStatePath];
	[super applicationWillSuspend];
}

- (void) applicationWillResume
{
}

@end
